/*
 * Copyright 2025-2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package xyz.thoughtset.viewer.ai.mcp.client.factory;

import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.Tool;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.model.ModelOptionsUtils;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.definition.DefaultToolDefinition;
import org.springframework.ai.tool.definition.ToolDefinition;
import org.springframework.ai.tool.execution.ToolExecutionException;
import org.springframework.ai.tool.metadata.ToolMetadata;
import xyz.thoughtset.viewer.ai.mcp.client.entity.McpClientLink;

import java.util.Map;

@Slf4j
public class McpToolCallback implements ToolCallback {
	private final ToolDefinition toolDefinition;
	private final McpClientLink mcpClient;
	private final String toolName;
	private final Tool tool;


	public McpToolCallback(McpClientLink mcpClient, Tool tool) {
		this.mcpClient = mcpClient;
		this.tool = tool;
		this.toolName = this.tool.name()+"#"+this.mcpClient.clientName();
		this.toolDefinition = DefaultToolDefinition.builder()
				.name(toolName)
				.description(this.tool.description())
				.inputSchema(ModelOptionsUtils.toJsonString(this.tool.inputSchema()))
				.build();
	}


	@Override
	public ToolDefinition getToolDefinition() {
		return this.toolDefinition;
	}

	@Override
	public ToolMetadata getToolMetadata() {
		return ToolCallback.super.getToolMetadata();
	}

	public String getOriginalToolName() {
		return this.tool.name();
	}


	@Override
	public String call(String functionInput) {
		Map<String, Object> arguments = ModelOptionsUtils.jsonToMap(functionInput);
		log.debug("***** *****"+toolName+" call with arguments: {}", arguments);
		CallToolResult response;
		try {
			response = this.mcpClient.mcpSyncClient().callTool(new CallToolRequest(this.tool.name(), arguments));
		}
		catch (Exception ex) {
			log.error("Exception while tool calling: ", ex);
			throw new ToolExecutionException(this.getToolDefinition(), ex);
		}

		if (response.isError() != null && response.isError()) {
			log.error("Error calling tool: {}", response.content());
			throw new ToolExecutionException(this.getToolDefinition(),
					new IllegalStateException("Error calling tool: " + response.content()));
		}
		return ModelOptionsUtils.toJsonString(response.content());
	}

	@Override
	public String call(String toolArguments, ToolContext toolContext) {
		return this.call(toolArguments);
	}

}
